package models;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;

import org.apache.commons.io.IOUtils;

import play.Play;
import play.data.validation.MaxSize;
import play.db.jpa.Model;

import commons.Metadata;

import controllers.ImageController;

@Entity
public class Image extends Model {
    @ManyToOne(fetch = FetchType.LAZY)
    public Post post;
    public String contentType;
    public String uuid;
    @MaxSize(value = 128)
    public String title;
    int width, height;
    public boolean isTheMainImage;

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }

    public Image(String name, InputStream is) throws IOException {
        super();
        // Destination directory
        File imageDir = new File(Play.configuration.getProperty("images.path"));
        // if not, create
        if (!imageDir.exists()) {
            imageDir.mkdirs(); // create new dir if not present
        }
        // Move file to new directory
        UUID uuid = UUID.randomUUID();
        File newfile = new File(imageDir, uuid.toString());
        OutputStream os = null;
        try {
            os = new FileOutputStream(newfile);
            IOUtils.copy(is, os);
            os.flush();
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        }

        this.title = name;
        this.uuid = uuid.toString();
        // Parse metadata
        Metadata m = new Metadata(newfile);
        this.width = m.width;
        this.height = m.height;
        // TODO : get title and description from exif
        // Save it
        this.save();
    }

    public Image() {
        super();
    }

    public void setImageAsTheMainOne() {
        if (this.post != null) {
            for (Image image : this.post.images) {
                image.isTheMainImage = false;
            }
        }
        this.isTheMainImage = true;
    }

    public String getUrl(String command) {
        return "/image/" + ImageController.encodePath(this.uuid, command);
    }

    public String getSmallUrl() {
        return getUrl("/resize-if-bigger/256");
    }
    
    public String getMediumUrl() {
        return getUrl("/resize-if-bigger/512");
    }
    
    public String getUrl() {
        return getUrl("/resize-if-bigger/1024");
    }

    public String getThumbnailUrl() {
        return getUrl("/crop/266");
    }

    public String getMiniThumbnailUrl() {
        return getUrl("/crop/48");
    }
    

}
